package com.lcg.word

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lcg.base.Loading
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 基础
 *
 * @author lei.chuguang Email:475825657@qq.com
 */
@Composable
@Preview
fun Base(
    vm: BaseViewModel = BaseViewModel().apply { title = "标题" },
    content: @Composable ColumnScope.() -> Unit = {}
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        Column(
            Modifier
                .fillMaxSize()
        ) {
            if (vm.showBack || vm.title.isNotEmpty())
                TopBar(vm)
            content()
        }
        if (vm.showLoading) Loading(vm)
    }
}

/**标题栏*/
@Composable
fun TopBar(vm: BaseViewModel) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(48.dp)
    ) {
        if (vm.showBack)
            Icon(
                imageVector = Icons.Default.ArrowBack,
                contentDescription = "返回",
                modifier = Modifier
                    .size(48.dp)
                    .clickable(onClick = { vm.back() })
                    .padding(10.dp),
                tint = Color.Black
            )
        if (vm.title.isNotEmpty())
            Text(
                text = vm.title,
                color = Color.Black,
                modifier = Modifier
                    .align(alignment = Alignment.Center),
                fontSize = 18.sp
            )
        if (vm.rightText.isNotEmpty())
            Box(
                modifier = Modifier
                    .height(48.dp)
                    .clickable { vm.clickRight() }
                    .padding(10.dp)
                    .align(alignment = Alignment.CenterEnd), contentAlignment = Alignment.Center
            ) {
                Text(
                    text = vm.rightText,
                    color = Color.Blue,
                    fontSize = 18.sp,
                    textDecoration = TextDecoration.Underline
                )
            }
    }
}

/**基础ViewModel*/
open class BaseViewModel : ViewModel(), Loading {
    var showBack by mutableStateOf(true)
    var title by mutableStateOf("")
    var rightText by mutableStateOf("")
    var navigator: DestinationsNavigator? = null
    open fun back() {
        navigator?.navigateUp()
    }

    open fun clickRight() {}

    /**显示load对话框，用于UI*/
    var showLoading by mutableStateOf(false)
        private set
    override var loadingMessage by mutableStateOf("加载中...")

    @Volatile
    override var isLoading = false
    override var job: Job? = null

    /**是否可取消*/
    var loadingCancelable = true

    /**load延迟显示时间*/
    var loadingUiDelay = 500L
    private var uiDelayJob: Job? = null
    override fun show(job: Job?) {
        super.show(job)
        if (loadingUiDelay > 0) {
            uiDelayJob = viewModelScope.launch(Dispatchers.IO) {
                delay(loadingUiDelay)
                showLoading = true
            }
        } else {
            showLoading = true
        }
    }

    override fun dismiss() {
        super.dismiss()
        if (uiDelayJob?.isCompleted != true)
            uiDelayJob?.cancel()
        uiDelayJob = null
        //
        showLoading = false
    }

    override fun cancelJob() {
        if (loadingCancelable)
            super.cancelJob()
    }
}

@Composable
fun Loading(loading: Loading) {
    Box(modifier = Modifier
        .fillMaxSize()
        .clickable {
            loading.cancelJob()
        }) {
        Row(
            modifier = Modifier
                .align(Alignment.Center)
                .background(color = Color(0x7F333333), shape = RoundedCornerShape(5.dp))
                .padding(12.dp, 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            CircularProgressIndicator(
                modifier = Modifier.size(20.dp),
                color = Color.White,
                strokeWidth = 2.dp
            )
            Spacer(modifier = Modifier.size(12.dp))
            Text(text = loading.loadingMessage, color = Color.White)
        }
    }
}